import { createSignal, type Component } from "solid-js";
import style from "./TimeInput.module.scss";

interface TimeInputProps {
  value: string;
  isAlarm?: boolean;
  class?: string;
  onChange: (value: string) => void;
}

const TimeInput: Component<TimeInputProps> = (props) => {
  // 解析初始值为数字类型
  const parseInitialValue = (value: string) => {
    const parts = value.split(":");
    return {
      hours: parseInt(parts[0] || "0") || 0,
      minutes: parseInt(parts[1] || "0") || 0,
      seconds: parseInt(parts[2] || "0") || 0,
    };
  };

  const initialValues = parseInitialValue(props.value);
  const [rawHours, setRawHours] = createSignal(initialValues.hours);
  const [rawMinutes, setRawMinutes] = createSignal(initialValues.minutes);
  const [rawSeconds, setRawSeconds] = createSignal(initialValues.seconds);
  const [focusedPart, setFocusedPart] = createSignal<"hours" | "minutes" | "seconds" | null>(null);

  const handleTimeChange = (
    part: "hours" | "minutes" | "seconds",
    value: string,
    element: HTMLInputElement
  ) => {
    // 清理非数字字符
    const numericValue = value.replace(/\D/g, "") || "0";
    let numValue = Math.max(0, parseInt(numericValue));

    // 设置数值范围限制
    if (part === "hours") {
      numValue = props.isAlarm ? Math.min(numValue, 23) : Math.min(numValue, 99);
    } else {
      numValue = Math.min(numValue, 59);
    }

    // 更新对应状态
    switch (part) {
      case "hours":
        setRawHours(numValue);
        break;
      case "minutes":
        setRawMinutes(numValue);
        break;
      case "seconds":
        setRawSeconds(numValue);
        break;
    }

    // 触发父组件更新（始终使用补零格式）
    props.onChange(
      `${rawHours().toString().padStart(2, "0")}:${rawMinutes()
        .toString()
        .padStart(2, "0")}:${rawSeconds().toString().padStart(2, "0")}`
    );

    // 自动跳转逻辑（当输入两位时跳转）
    if (numericValue.length >= 2) {
      const nextInput = element.nextElementSibling?.nextElementSibling as HTMLInputElement;
      nextInput?.focus();
      nextInput?.select();
    }
  };

  // 动态显示值（聚焦时显示原始值，非聚焦时显示补零值）
  const getDisplayValue = (part: "hours" | "minutes" | "seconds") => {
    const value = {
      hours: rawHours(),
      minutes: rawMinutes(),
      seconds: rawSeconds(),
    }[part];
    return focusedPart() === part ? value.toString() : value.toString().padStart(2, "0");
  };

  return (
    <div class={`${style.timeInput} ${props.class}`}>
      <input
        type="text"
        pattern="\d*"
        maxLength={2}
        inputMode="numeric"
        value={getDisplayValue("hours")}
        onInput={(e) => handleTimeChange("hours", e.currentTarget.value, e.currentTarget)}
        onFocus={(e) => {
          setFocusedPart("hours");
          e.currentTarget.select();
        }}
        onBlur={() => setFocusedPart(null)}
      />
      <span>:</span>
      <input
        type="text"
        pattern="\d*"
        maxLength={2}
        inputMode="numeric"
        value={getDisplayValue("minutes")}
        onInput={(e) => handleTimeChange("minutes", e.currentTarget.value, e.currentTarget)}
        onFocus={(e) => {
          setFocusedPart("minutes");
          e.currentTarget.select();
        }}
        onBlur={() => setFocusedPart(null)}
      />
      <span>:</span>
      <input
        type="text"
        pattern="\d*"
        maxLength={2}
        inputMode="numeric"
        value={getDisplayValue("seconds")}
        onInput={(e) => handleTimeChange("seconds", e.currentTarget.value, e.currentTarget)}
        onFocus={(e) => {
          setFocusedPart("seconds");
          e.currentTarget.select();
        }}
        onBlur={() => setFocusedPart(null)}
      />
    </div>
  );
};

export default TimeInput;